package processor

import (
	"fmt"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"os"
)

// StopApplication 停止应用
func (cls *Processor) StopApplication(name string) error {
	cls.mutex.RLock()
	defer cls.mutex.RUnlock()

	if application, ok := cls.application[name]; ok {
		if StateStarted != application.state {
			return nil
		}

		application.quiting = true
		application.state = StateStopping
		application.callback(StateStopping, nil)
		if err := application.c.Process.Signal(os.Interrupt); nil != err {
			application.state = StateStarted
			application.callback(StateStarted, fmt.Errorf("停止应用失败: %s", err))

			return err
		}

		// 等待进程结束
		_ = application.c.Wait()

		// 释放进程对象
		application.c = nil

		// 关闭文件不返回失败状态
		if err := application.output.Close(); nil != err {
			logger.GetLogger().Sugar().Errorf("进程管理器: 关闭应用输出文件失败，%s", err)
		}

		application.state = StateStopped
		application.callback(StateStopped, nil)
	}

	return nil
}
